/**
 * 构造树型结构数据
 * @param {*} data 数据源
 * @param {*} id id字段 默认 'id'
 * @param {*} parentId 父节点字段 默认 'parentId'
 * @param {*} children 孩子节点字段 默认 'children'
 */
export const handleTree = (data, id, parentId, children) => {
  if (!Array.isArray(data)) {
    console.warn('data must be an array')
    return []
  }
  
  const config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children'
  }

  const childrenListMap = {}
  const nodeIds = {}
  const tree = []

  // 第一遍遍历：构建映射关系
  for (let i = 0; i < data.length; i++) {
    const d = data[i]
    const pid = d[config.parentId]
    if (childrenListMap[pid] == null) {
      childrenListMap[pid] = []
    }
    nodeIds[d[config.id]] = d
    childrenListMap[pid].push(d)
  }

  // 第二遍遍历：找到根节点
  for (let i = 0; i < data.length; i++) {
    const d = data[i]
    const pid = d[config.parentId]
    if (nodeIds[pid] == null) {
      tree.push(d)
    }
  }

  // 递归构建树形结构
  for (let i = 0; i < tree.length; i++) {
    adaptToChildrenList(tree[i])
  }

  function adaptToChildrenList(o) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]]
    }
    if (o[config.childrenList]) {
      for (let j = 0; j < o[config.childrenList].length; j++) {
        adaptToChildrenList(o[config.childrenList][j])
      }
    }
  }

  return tree
}